package com.common.servlet.abstracts;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.security.abstracts.AbstractException;
import com.common.security.exceptions.ManagerException;

public abstract class AbstractSimpleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected static Logger logger = Logger.getAnonymousLogger();

	public final void doGet(HttpServletRequest request, HttpServletResponse response) {
		try {
			handle(request, response);
		} catch (ManagerException managerException) {
			managerException.printStackTrace();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	public final void doPost(HttpServletRequest request, HttpServletResponse response) {
		doGet(request, response);
	}

	public abstract void handle(HttpServletRequest request, HttpServletResponse response) throws ManagerException, IOException;
	
	public abstract AbstractJSONParser parser();
	
	/*
	 * Not used
	public void error(AbstractError error, HttpServletResponse response) {
		try {
			logger.severe(error.getCode() + " " + error.getMessage());
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseError(error));
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/

	/**
	 * This method converts exceptions into errors and sends them to the client.
	 * 
	 * <p>
	 * This is part of the new architecture as presented. The AbstractServlet converts the
	 * received request message into a Request. It is expected that the parser will throw
	 * exceptions and this method should convert them into errors and respond to the client.
	 * </p>
	 */
	public void exception(AbstractException exception, HttpServletResponse response) {
		try {
			logger.severe(exception.getCode() + " " + exception.getMessage());
			response.setContentType("json");
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * This method converts Runtime Exception into errors and send them to the clients.
	 */
	/*
	 * Not used
	public void exception(AbstractRuntimeException exception, HttpServletResponse response) {
		try {
			logger.severe(exception.getCode() + " " + exception.getMessage());
			response.setContentType("text/xml");
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/
}
